package 反射;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class SQL语言封装
{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        TestClass t = new TestClass(10,"11","12");
        function(t);
    }
    public static void function(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String sql = "insert into ";
        Class aC = obj.getClass();
        String cname = aC.getName();
        cname = cname.substring(cname.lastIndexOf(".")+1);
        sql += cname+"(";
        Method[] methods = aC.getMethods();
        List<String> res = new ArrayList<String>();
        for (Method m:methods) {
            String mname = m.getName();
            if (mname.startsWith("set")){
                String setname = "get"+mname.substring(3);
                Object resO = aC.getMethod(setname,null).invoke(obj,null);
                res.add(resO.toString());
                 mname = mname.substring(3);
                 sql+=mname+",";
            }
        }
        sql = sql.substring(0,sql.length()-1)+") values (";
        for (String s:res) {
            sql += "'"+s+"',";
        }
        sql = sql.substring(0,sql.length()-1)+") ";

        System.out.println(sql);
    }

}
